package com.java.mywxmp.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.mywxmp.builder.TextBuilder;
import com.java.mywxmp.constant.UserConstant;
import com.java.mywxmp.entity.User;
import com.java.mywxmp.service.UserService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 用户关注公众号事件
 */
@Component
@AllArgsConstructor
public class SubscribeHandler extends AbstractHandler {
    private final UserService userService;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息 (个人订阅号没有这个接口的权限!!!)
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // 查询用户是否曾经关注过又取关
                User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, userWxInfo.getOpenId()));
                if (one == null) {
                    User user = new User();
                    user.setOpenid(userWxInfo.getOpenId());
                    user.setNickname(userWxInfo.getNickname());
                    user.setSex(userWxInfo.getSex());
                    user.setCountry(userWxInfo.getCountry());
                    user.setProvince(userWxInfo.getProvince());
                    user.setCity(userWxInfo.getCity());
                    user.setHeadImgUrl(userWxInfo.getHeadImgUrl());
                    user.setSubscribeTime(new Date());
                    userService.save(user);
                } else {
                    // 修改状态为关注
                    one.setStatus(UserConstant.FOLLOW);
                    userService.updateById(one);
                }

            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
                // 查询用户是否曾经关注过又取关
                User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, wxMessage.getFromUser()));
                if (one == null) {
                    User user = new User();
                    user.setOpenid(wxMessage.getFromUser());
                    user.setSubscribeTime(new Date());
                    userService.save(user);
                } else {
                    // 修改状态为关注
                    one.setStatus(UserConstant.FOLLOW);
                    userService.updateById(one);
                }
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注！本公众号主要发布java相关学习资料，与大家一起学习，共同进步，收获更多的机会，实现财富自由~~~", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

}
